<template>
	<div class="predict-container">
		<h2>成绩统计</h2>

		<el-card class="filter-card">
			<div class="card-header">
				<div class="filter-section">
					<el-select v-model="selectedSubject" placeholder="请选择科目" class="filter-item">
						<el-option
							v-for="subject in subjectList"
							:key="subject.value"
							:label="subject.label"
							:value="subject.value"
						/>
					</el-select>

					<el-button type="primary" @click="fetchPredictData" :disabled="!canFetchData"
						>查询</el-button
					>
				</div>

				<!-- 数据模式切换和AI分析 -->
				<div v-if="hasPredictionData" class="mode-ai-section">
					<div class="mode-switch-section">
						<span class="mode-label">数据模式：</span>
						<el-radio-group v-model="displayMode" size="default">
							<el-radio-button label="theory">理论成绩</el-radio-button>
							<el-radio-button label="practice">实践成绩</el-radio-button>
						</el-radio-group>
					</div>
					<el-button
						type="primary"
						@click="showAiDrawer"
						size="default"
						:disabled="!hasPredictionData"
					>
						<el-icon><ChatLineRound /></el-icon> AI分析
					</el-button>
				</div>
			</div>
		</el-card>

		<div v-if="loading" class="loading-container">
			<el-skeleton :rows="10" animated />
		</div>

		<div v-else-if="predictData" class="chart-container">
			<!-- 平均分统计图表 -->
			<el-card v-if="hasPredictionData" class="chart-card">
				<template #header>
					<div class="card-header">
						<h3>{{ displayMode === 'theory' ? '理论平均分统计' : '实践平均分统计' }}</h3>
					</div>
				</template>

				<div class="chart-wrapper">
					<div class="chart-item">
						<avg-score :data="avgScoreData?.[displayMode]" width="100%" height="400px" />
					</div>
				</div>
			</el-card>

			<!-- 及格率/优秀率统计图表 - 左右布局 -->
			<div class="rate-charts-container">
				<el-card v-if="hasPredictionData" class="chart-card rate-chart">
					<template #header>
						<div class="card-header">
							<h3>{{ displayMode === 'theory' ? '理论及格率统计' : '实践及格率统计' }}</h3>
						</div>
					</template>

					<div class="chart-wrapper">
						<div class="chart-item">
							<pass-excellent
								:data="theoryPassExcellentData?.[displayMode]"
								width="100%"
								height="400px"
							/>
						</div>
					</div>
				</el-card>

				<el-card v-if="hasPredictionData" class="chart-card rate-chart">
					<template #header>
						<div class="card-header">
							<h3>{{ displayMode === 'theory' ? '理论优秀率统计' : '实践优秀率统计' }}</h3>
						</div>
					</template>

					<div class="chart-wrapper">
						<div class="chart-item">
							<pass-excellent
								:data="practicePassExcellentData?.[displayMode]"
								width="100%"
								height="400px"
							/>
						</div>
					</div>
				</el-card>
			</div>
		</div>

		<div v-else class="empty-data">
			<el-empty description="请选择科目查看统计数据" />
		</div>

		<!-- AI建议侧边栏 -->
		<el-drawer
			v-model="drawerVisible"
			title="AI分析建议"
			direction="rtl"
			size="30%"
			:destroy-on-close="false"
			:before-close="handleDrawerClose"
		>
			<div class="ai-drawer-content">
				<div v-if="aiLoading" class="ai-loading">
					<el-skeleton :rows="10" animated />
				</div>
				<div v-else-if="aiSuggestion" class="ai-suggestion">
					<div v-html="formattedAiSuggestion" ref="aiContentRef"></div>
				</div>
				<div v-else class="ai-empty">
					<el-empty description="点击下方按钮获取AI分析建议" />
				</div>
			</div>
			<template #footer>
				<div class="ai-drawer-footer">
					<el-button @click="drawerVisible = false">关闭</el-button>
					<el-button type="primary" @click="fetchAiSuggestion" :loading="aiLoading">
						{{ aiSuggestion ? '重新分析' : '获取AI分析' }}
					</el-button>
				</div>
			</template>
		</el-drawer>
	</div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { getTeacherSubjectDataService } from '@/api/predict'
import { ElMessage } from 'element-plus'
import { getSubjectListService } from '@/api/education/subject'
import AvgScore from './component/avgScore.vue'
import PassExcellent from './component/passExcellent.vue'
import { getAiAnswerService } from '@/api/ai'
import { ChatLineRound } from '@element-plus/icons-vue'
import { useAiStore } from '@/stores/modules/ai'
import { getScoreTotalService } from '@/api/education/scoreTotal'
import { getScoreStatsListService } from '@/api/education/scoreStats'

// 获取AI存储
const aiStore = useAiStore()

// 数据状态定义
const loading = ref(false)
const predictData = ref<any>(null)

// AI建议相关状态
const aiLoading = ref(false)
const aiSuggestion = ref('')
const drawerVisible = ref(false)
const streamIndex = ref(0)
const streamInterval = ref<number | null>(null)

// 科目列表
const subjectList = ref<Array<{ value: number; label: string }>>([])
const selectedSubject = ref<number | ''>('')

// 图表数据
const avgScoreData = ref<any>(null)
const theoryPassExcellentData = ref<any>(null)
const practicePassExcellentData = ref<any>(null)

// 添加显示模式切换
const displayMode = ref<'theory' | 'practice'>('theory')

// 添加计算属性判断是否可以查询
const canFetchData = computed(() => {
	return !!selectedSubject.value
})

// 添加计算属性判断是否有预测数据
const hasPredictionData = computed(() => {
	return predictData.value && Array.isArray(predictData.value) && predictData.value.length > 0
})

// 格式化AI建议，只取正常格式的后半部分
const formattedAiSuggestion = computed(() => {
	if (!aiSuggestion.value) return ''

	// 找到正常格式数据的开始位置（以 ### 开头的部分）
	const normalDataStart = aiSuggestion.value.indexOf('### 科目成绩表现分析与建议')

	if (normalDataStart === -1) {
		// 如果没找到标准格式，返回原始数据
		return `<pre style="white-space: pre-wrap; font-family: inherit;">${aiSuggestion.value}</pre>`
	}

	// 只取正常格式的部分
	let text = aiSuggestion.value.substring(normalDataStart).trim()

	// 进行基本格式化
	text = text
		// 处理主标题
		.replace(/^###\s+(.+)$/gm, '<h3 class="ai-title">$1</h3>')
		// 处理四级标题
		.replace(/^####\s+(.+)$/gm, '<h4 class="ai-subtitle">$1</h4>')
		// 处理编号列表
		.replace(/^(\d+)\.\s+(.+)$/gm, '<div class="ai-item"><strong>$1.</strong> $2</div>')
		// 处理加粗
		.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
		// 处理换行
		.replace(/\n/g, '<br>')

	// 简单的关键词高亮
	text = text
		.replace(/(20\d{2}级)/g, '<span class="highlight">$1</span>')
		.replace(/(105班|106班)/g, '<span class="highlight">$1</span>')
		.replace(/(\d+\.?\d*%)/g, '<span class="percent">$1</span>')

	return `<div class="ai-simple">${text}</div>`
})

// 显示AI侧边栏
const showAiDrawer = () => {
	drawerVisible.value = true

	// 检查是否有Pinia中的缓存数据
	const cachedSuggestion = aiStore.aiSuggestion[Number(selectedSubject.value)]
	if (cachedSuggestion) {
		aiSuggestion.value = cachedSuggestion
	} else if (!aiSuggestion.value) {
		// 如果没有缓存且没有当前数据，则获取新数据
		fetchAiSuggestion()
	}
}

// 关闭侧边栏前的处理
const handleDrawerClose = () => {
	// 如果正在加载，取消关闭
	if (aiLoading.value) {
		ElMessage.warning('正在获取AI分析，请稍候...')
		return false
	}

	// 停止流式显示
	if (streamInterval.value) {
		clearInterval(streamInterval.value)
		streamInterval.value = null
	}

	drawerVisible.value = false
	return true
}

// 获取科目列表
const fetchSubjectList = async () => {
	try {
		const res = await getSubjectListService()
		if (res.data && res.data.code === 1) {
			subjectList.value = res.data.data.map((subject: any) => ({
				value: subject.id,
				label: subject.subject
			}))

			// 默认选择第一个科目
			if (subjectList.value.length > 0) {
				selectedSubject.value = subjectList.value[0].value
				// 自动获取第一个科目的数据
				fetchPredictData()
			}
		} else {
			ElMessage.error('获取科目列表失败')
		}
	} catch (error) {
		console.error('获取科目列表失败:', error)
		ElMessage.error('获取科目列表失败，请重试')
	}
}

// 获取预测数据 - 只需要科目ID
const fetchPredictData = async () => {
	if (!selectedSubject.value) {
		ElMessage.warning('请选择科目')
		return
	}

	loading.value = true
	// 重置AI建议
	aiSuggestion.value = ''
	streamIndex.value = 0

	// 停止流式显示
	if (streamInterval.value) {
		clearInterval(streamInterval.value)
		streamInterval.value = null
	}

	try {
		// const res = await getTeacherSubjectDataService({
		// 	subjectId: Number(selectedSubject.value)
		// })

		const res = await getScoreStatsListService({
			subjectId: Number(selectedSubject.value)
		})

		console.log('获取预测数据:', res.data.data)

		if (res.data && res.data.code === 1) {
			predictData.value = res.data.data

			// 检查是否有统计数据（新的数据格式是数组）
			if (predictData.value && Array.isArray(predictData.value) && predictData.value.length > 0) {
				// 处理数据为图表组件需要的格式
				processChartData()
			} else {
				ElMessage.warning('未获取到统计数据')
				predictData.value = null
				avgScoreData.value = null
				theoryPassExcellentData.value = null
				practicePassExcellentData.value = null
			}
		} else {
			ElMessage.warning('未获取到统计数据')
			predictData.value = null
			avgScoreData.value = null
			theoryPassExcellentData.value = null
			practicePassExcellentData.value = null
		}
	} catch (error) {
		console.error('获取预测数据失败:', error)
		ElMessage.error('获取预测数据失败，请重试')
		predictData.value = null
		avgScoreData.value = null
		theoryPassExcellentData.value = null
		practicePassExcellentData.value = null
	} finally {
		loading.value = false
	}
}

// 处理数据为图表组件需要的格式
const processChartData = () => {
	if (!predictData.value || !Array.isArray(predictData.value) || predictData.value.length === 0) {
		return
	}

	// 获取所有年级（去重并排序）
	const allGrades = [...new Set(predictData.value.map((item: any) => item.grade))].sort(
		(a, b) => a - b
	)

	// 获取所有班级名称（去重）
	const allClassNames = [...new Set(predictData.value.map((item: any) => item.classname))]

	// 格式化数值的辅助函数
	const formatValue = (value: any) => {
		if (value === null || value === undefined) return null
		const numValue = parseFloat(value)
		if (isNaN(numValue)) return null
		return parseFloat(numValue.toFixed(2))
	}

	// 构建平均分数据
	const avgScoreSeriesData: {
		theoryData: Array<{ name: string; data: (number | null)[] }>
		practiceData: Array<{ name: string; data: (number | null)[] }>
	} = {
		theoryData: [],
		practiceData: []
	}

	// 构建及格率数据
	const passRateSeriesData: {
		theoryData: Array<{ name: string; data: (number | null)[] }>
		practiceData: Array<{ name: string; data: (number | null)[] }>
	} = {
		theoryData: [],
		practiceData: []
	}

	// 构建优秀率数据
	const excellentRateSeriesData: {
		theoryData: Array<{ name: string; data: (number | null)[] }>
		practiceData: Array<{ name: string; data: (number | null)[] }>
	} = {
		theoryData: [],
		practiceData: []
	}

	// 为每个班级构建数据系列
	allClassNames.forEach((className) => {
		// 理论平均分数据
		const theoryAvgData = allGrades.map((grade) => {
			const item = predictData.value.find(
				(d: any) => d.grade === grade && d.classname === className
			)
			return item ? formatValue(item.avgScoreTheory) : null
		})

		// 实践平均分数据
		const practiceAvgData = allGrades.map((grade) => {
			const item = predictData.value.find(
				(d: any) => d.grade === grade && d.classname === className
			)
			return item ? formatValue(item.avgScorePractice) : null
		})

		// 理论及格率数据
		const theoryPassData = allGrades.map((grade) => {
			const item = predictData.value.find(
				(d: any) => d.grade === grade && d.classname === className
			)
			return item ? formatValue(item.passRateTheory) : null
		})

		// 实践及格率数据
		const practicePassData = allGrades.map((grade) => {
			const item = predictData.value.find(
				(d: any) => d.grade === grade && d.classname === className
			)
			return item ? formatValue(item.passRatePractice) : null
		})

		// 理论优秀率数据
		const theoryExcellentData = allGrades.map((grade) => {
			const item = predictData.value.find(
				(d: any) => d.grade === grade && d.classname === className
			)
			return item ? formatValue(item.excellentRateTheory) : null
		})

		// 实践优秀率数据
		const practiceExcellentData = allGrades.map((grade) => {
			const item = predictData.value.find(
				(d: any) => d.grade === grade && d.classname === className
			)
			return item ? formatValue(item.excellentRatePractice) : null
		})

		// 添加到系列数据中
		avgScoreSeriesData.theoryData.push({
			name: `${className}班`,
			data: theoryAvgData
		})
		avgScoreSeriesData.practiceData.push({
			name: `${className}班`,
			data: practiceAvgData
		})

		passRateSeriesData.theoryData.push({
			name: `${className}班`,
			data: theoryPassData
		})
		passRateSeriesData.practiceData.push({
			name: `${className}班`,
			data: practicePassData
		})

		excellentRateSeriesData.theoryData.push({
			name: `${className}班`,
			data: theoryExcellentData
		})
		excellentRateSeriesData.practiceData.push({
			name: `${className}班`,
			data: practiceExcellentData
		})
	})

	// 设置平均分图表数据 - 分理论和实践
	avgScoreData.value = {
		theory: {
			text: '平均分统计',
			grades: allGrades,
			series: avgScoreSeriesData.theoryData
		},
		practice: {
			text: '平均分统计',
			grades: allGrades,
			series: avgScoreSeriesData.practiceData
		}
	}

	// 设置及格率图表数据 - 分理论和实践
	theoryPassExcellentData.value = {
		theory: {
			text: '及格率统计',
			grades: allGrades,
			series: passRateSeriesData.theoryData
		},
		practice: {
			text: '及格率统计',
			grades: allGrades,
			series: passRateSeriesData.practiceData
		}
	}

	// 设置优秀率图表数据 - 分理论和实践
	practicePassExcellentData.value = {
		theory: {
			text: '优秀率统计',
			grades: allGrades,
			series: excellentRateSeriesData.theoryData
		},
		practice: {
			text: '优秀率统计',
			grades: allGrades,
			series: excellentRateSeriesData.practiceData
		}
	}
}

// 处理SSE流式响应
const handleSSEResponse = async (response: any) => {
	console.log('=== SSE流式处理开始 ===')

	// 获取响应的reader
	const reader = response.body.getReader()
	const decoder = new TextDecoder()

	// 清空当前建议内容
	aiSuggestion.value = ''
	console.log('已清空aiSuggestion.value')

	// 用于存储完整响应
	let completeResponse = ''
	let chunkCount = 0

	try {
		// 处理数据流
		while (true) {
			const { done, value } = await reader.read()
			if (done) {
				console.log('SSE流读取完毕，总共处理了', chunkCount, '个数据块')
				break
			}

			chunkCount++
			console.log(`处理第${chunkCount}个数据块`)

			// 解码二进制数据
			const chunk = decoder.decode(value, { stream: true })
			console.log('当前chunk内容:', chunk.substring(0, 100) + '...')

			// 解析SSE格式数据
			const lines = chunk.split('\n')
			for (const line of lines) {
				if (line.startsWith('data:')) {
					const data = line.substring(5).trim()
					if (
						data &&
						data !== '[DONE]' &&
						data !== '回答生成完毕' &&
						!data.startsWith('开始生成回答')
					) {
						// 累加到完整响应
						completeResponse += data + '\n'
						console.log('累加数据，当前总长度:', completeResponse.length)
					}
				}
			}

			// 直接更新显示内容
			console.log('更新aiSuggestion.value，长度:', completeResponse.length)
			aiSuggestion.value = completeResponse

			// 自动滚动到底部
			scrollToBottom()
		}

		// 确保最终数据被正确设置
		console.log('最终设置aiSuggestion.value，长度:', completeResponse.length)
		aiSuggestion.value = completeResponse

		// 完成后保存到Pinia存储
		aiStore.saveAiSuggestion(Number(selectedSubject.value), aiSuggestion.value)
		console.log('已保存到Pinia存储')
		console.log('=== SSE流式处理结束 ===')
	} catch (error) {
		console.error('读取SSE流出错:', error)
		throw error
	} finally {
		// 确保reader关闭
		reader.releaseLock()
	}
}

// 滚动到底部
const scrollToBottom = () => {
	const contentRef = document.querySelector('.ai-drawer-content')
	if (contentRef) {
		setTimeout(() => {
			contentRef.scrollTop = contentRef.scrollHeight
		}, 0)
	}
}

// 获取ai建议
const fetchAiSuggestion = async () => {
	if (!predictData.value) {
		ElMessage.warning('请先获取统计数据')
		return
	}

	// 检查是否是重新分析请求
	const isReanalysis = aiSuggestion.value !== ''

	// 如果不是重新分析，先尝试从Pinia存储获取
	if (!isReanalysis) {
		const cachedSuggestion = aiStore.aiSuggestion[Number(selectedSubject.value)]
		if (cachedSuggestion) {
			aiSuggestion.value = cachedSuggestion
			return
		}
	}

	aiLoading.value = true
	aiSuggestion.value = ''

	// 停止之前的流式显示
	if (streamInterval.value) {
		clearInterval(streamInterval.value)
		streamInterval.value = null
	}

	try {
		// 创建请求参数
		const params = {
			message:
				'请根据当前科目的统计数据给出你的分析与建议，其中包括各班级（属性名：classname）各年级（属性名：grade）的成绩表现分析、趋势分析，并提出改进建议（其中的数据为0或null时，可能表示数据不存在或该年级班级未学习该科目）:' +
				JSON.stringify(predictData.value)
		}

		// 使用getAiAnswerService函数获取响应
		const res = await getAiAnswerService(params)

		// 检查响应格式
		if (res && res.data) {
			// 如果是字符串且包含SSE格式数据
			if (
				typeof res.data === 'string' &&
				(res.data.includes('event:') || res.data.includes('data:'))
			) {
				// 创建一个模拟的Response对象
				const stream = new ReadableStream({
					start(controller) {
						// 将字符串转换为Uint8Array
						const encoder = new TextEncoder()
						const uint8Array = encoder.encode(res.data)
						controller.enqueue(uint8Array)
						controller.close()
					}
				})

				// 创建Response对象
				const response = new Response(stream)

				// 处理SSE流式响应
				await handleSSEResponse(response)
			} else if (res.data.code === 1 && res.data.data) {
				// 标准格式响应
				aiSuggestion.value = res.data.data
				// 保存到Pinia存储
				aiStore.saveAiSuggestion(Number(selectedSubject.value), aiSuggestion.value)
			} else {
				// 其他格式
				aiSuggestion.value = typeof res.data === 'string' ? res.data : JSON.stringify(res.data)
				// 保存到Pinia存储
				aiStore.saveAiSuggestion(Number(selectedSubject.value), aiSuggestion.value)
			}
		} else {
			throw new Error('获取AI建议失败')
		}
	} catch (error) {
		console.error('获取AI建议失败:', error)

		ElMessage({
			message: '获取AI建议失败，请稍后重试',
			type: 'error',
			duration: 3000
		})

		// 关闭抽屉
		drawerVisible.value = false
	} finally {
		aiLoading.value = false
	}
}

// 在组件卸载前清除定时器
onMounted(() => {
	fetchSubjectList()
})

// 添加onUnmounted钩子清除定时器
onUnmounted(() => {
	if (streamInterval.value) {
		clearInterval(streamInterval.value)
		streamInterval.value = null
	}
})
</script>

<style lang="scss" scoped>
.predict-container {
	padding: 20px;

	h2 {
		margin-top: 0;
	}
}

.filter-card {
	margin-bottom: 20px;
}

.mode-label {
	font-weight: 500;
	color: var(--el-text-color-regular);
	white-space: nowrap;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	flex-wrap: wrap;
	gap: 15px;
	/* margin-bottom: 15px; */
}

.filter-section {
	display: flex;
	gap: 15px;
	align-items: center;
}

.mode-ai-section {
	display: flex;
	gap: 15px;
	align-items: center;
	flex-wrap: wrap;
}

.mode-switch-section {
	display: flex;
	align-items: center;
	gap: 10px;
}

.filter-item {
	min-width: 240px;
}

.chart-container {
	display: flex;
	flex-direction: column;
	gap: 20px;
}

/* 新增左右布局容器样式 */
.rate-charts-container {
	display: flex;
	gap: 20px;
	margin-bottom: 20px;
}

.rate-chart {
	flex: 1;
	margin-bottom: 0;
}

.chart-card {
	margin-bottom: 20px;
}

.chart-wrapper {
	display: flex;
	flex-direction: column;
}

.chart-item {
	width: 100%;
	height: 450px;
	margin-bottom: 20px;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	border-radius: 4px;
	padding: 10px;
	background-color: #fff;
}

.loading-container {
	padding: 20px;
}

.empty-data {
	margin-top: 50px;
	display: flex;
	justify-content: center;
}

/* AI侧边栏样式 */
.ai-drawer-content {
	padding: 0 15px;
	height: calc(100% - 60px);
	overflow-y: auto;
	scroll-behavior: smooth;
}

.ai-drawer-footer {
	display: flex;
	justify-content: flex-end;
	padding: 10px 15px;
	border-top: 1px solid #e4e7ed;
}

.ai-suggestion {
	line-height: 1.6;
	font-size: 14px;
	padding-bottom: 20px;
}

/* 简化的AI内容样式 */
.ai-suggestion :deep(.ai-simple) {
	color: #333;
	line-height: 1.8;
}

/* 标题样式 */
.ai-suggestion :deep(.ai-title) {
	font-size: 16px;
	font-weight: bold;
	color: #1890ff;
	margin: 15px 0 10px 0;
	padding-bottom: 5px;
	border-bottom: 1px solid #e8e8e8;
}

/* 四级标题样式 */
.ai-suggestion :deep(.ai-subtitle) {
	font-size: 14px;
	font-weight: bold;
	color: #52c41a;
	margin: 12px 0 8px 0;
}

/* 编号列表项 */
.ai-suggestion :deep(.ai-item) {
	margin: 8px 0;
	padding: 8px 0;
	line-height: 1.6;
}

/* 简单高亮 */
.ai-suggestion :deep(.highlight) {
	color: #1890ff;
	font-weight: bold;
}

/* 百分比 */
.ai-suggestion :deep(.percent) {
	color: #f5222d;
	font-weight: bold;
}

/* 加粗文本 */
.ai-suggestion :deep(strong) {
	color: #262626;
	font-weight: bold;
}

.ai-loading,
.ai-empty {
	padding: 20px 0;
}

/* 添加响应式布局 */
@media (max-width: 1200px) {
	.rate-charts-container {
		flex-direction: column;
	}

	.rate-chart {
		margin-bottom: 20px;
	}
}

@media (max-width: 768px) {
	.card-header {
		flex-direction: column;
		align-items: flex-start;
	}

	.filter-section {
		width: 100%;
		justify-content: space-between;
	}

	.mode-ai-section {
		width: 100%;
		justify-content: space-between;
	}

	.filter-item {
		flex: 1;
		min-width: 200px;
	}
}
</style>
